% 读取Excel数据
data = readtable('附件1 数据-C题.xlsx');

% 数据清洗
% 1. 移除失业注销时间或失业时间为空的记录
data = data(~ismissing(data.c_ajc090), :); % 至少需要失业时间

% 2. 移除关键字段为空的记录
key_fields = {'age', 'sex', 'edu_level', 'c_aac183', 'b_aab022'};
data = data(~any(ismissing(data(:, key_fields)), 2), :);

% 3. 验证年龄、性别、学历的有效性
data = data(data.age >= 0 & data.age <= 100, :); % 年龄在0-100之间
data = data(ismember(data.sex, [1, 2]), :); % 性别为1或2
valid_edu = [10,11,12,13,14,15,16,17,18,19,20,21,22,23,28,30,31,32,33,...
             40,41,42,43,44,45,46,47,48,49,50,60,61,62,63,70,71,73,...
             80,81,83,90,91,92,93,99];
data = data(ismember(data.edu_level, valid_edu), :);

% 4. 转换日期格式并验证
try
    data.c_acc028 = datetime(data.c_acc028, 'InputFormat', 'yyyy-MM-dd HH:mm:ss');
    data.c_ajc090 = datetime(data.c_ajc090, 'InputFormat', 'yyyy-MM-dd HH:mm:ss');
catch
    % 如果日期格式不一致，尝试无时间部分
    data.c_acc028 = datetime(data.c_acc028, 'InputFormat', 'yyyy-MM-dd');
    data.c_ajc090 = datetime(data.c_ajc090, 'InputFormat', 'yyyy-MM-dd');
end
% 移除无效日期
data = data(~isnat(data.c_ajc090), :);

% 确定就业状态
data.employment_status = categorical(~ismissing(data.c_acc028) & (data.c_acc028 > data.c_ajc090), [true, false], {'就业', '失业'});

% 检查是否还有数据
if isempty(data)
    error('清洗后没有有效数据！');
end

% 处理年龄：分组为年龄段
age_bins = [0, 25, 35, 45, Inf];
age_labels = {'<25', '25-35', '35-45', '>45'};
data.age_group = discretize(data.age, age_bins, 'categorical', age_labels);

% 处理性别：转换为描述
sex_labels = {'男', '女'};
data.sex = categorical(data.sex, [1, 2], sex_labels);

% 处理学历：根据编码转换为描述
edu_map = containers.Map(...
    {'10','11','12','13','14','15','16','17','18','19', ... % 研究生及以上
     '20','21','22','23','28', ... % 本科
     '30','31','32','33', ... % 专科
     '40','41','42','43','44','45','46','47','48','49','91','92','93', ... % 中职
     '50','60','61','62','63','70','71','73','80','81','83','90', ... % 高中及以下
     '99'}, ... % 其他
    {'研究生及以上','研究生及以上','研究生及以上','研究生及以上','研究生及以上',...
     '研究生及以上','研究生及以上','研究生及以上','研究生及以上','研究生及以上',...
     '本科','本科','本科','本科','本科',...
     '专科','专科','专科','专科',...
     '中职','中职','中职','中职','中职','中职','中职','中职','中职','中职','中职','中职','中职',...
     '高中及以下','高中及以下','高中及以下','高中及以下','高中及以下',...
     '高中及以下','高中及以下','高中及以下','高中及以下','高中及以下',...
     '高中及以下','高中及以下',...
     '其他'});
data.edu = cell(height(data), 1);
for i = 1:height(data)
    edu_key = num2str(data.edu_level(i));
    if isKey(edu_map, edu_key)
        data.edu{i} = edu_map(edu_key);
    else
        data.edu{i} = '其他';
    end
end
data.edu = categorical(data.edu);

% 处理专业：简化为主要类别
data.prof = data.c_aac183;
data.prof = strrep(data.prof, '其他学科', '其他');
prof_categories = unique(data.prof);
if length(prof_categories) > 5
    prof_counts = groupcounts(data, 'prof');
    [~, idx] = sort([prof_counts.GroupCount], 'descend');
    top_profs = prof_categories(idx(1:min(4, length(idx))));
    data.prof(~ismember(data.prof, top_profs)) = {'其他'};
end
data.prof = categorical(data.prof);

% 处理行业：归并为五个类别
agri_codes = {'A'};
manu_codes = {'C'};
const_mining_codes = {'B', 'E'};
trade_trans_codes = {'F', 'G'};
service_codes = {'D', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'Z'};
data.industry = cell(height(data), 1);
for i = 1:height(data)
    code = string(data.b_aab022{i});
    code_prefix = extractBefore(code, 2);
    if ismember(code_prefix, agri_codes)
        data.industry{i} = '农业及相关产业';
    elseif ismember(code_prefix, manu_codes)
        data.industry{i} = '制造业';
    elseif ismember(code_prefix, const_mining_codes)
        data.industry{i} = '建筑及采矿业';
    elseif ismember(code_prefix, trade_trans_codes)
        data.industry{i} = '批发 批发零售及运输业';
    elseif ismember(code_prefix, service_codes)
        data.industry{i} = '服务业及其他';
    else
        data.industry{i} = '服务业及其他';
    end
end
data.industry = categorical(data.industry);







% 数据处理
counts = crosstab(data.employment_status);
if length(counts) < 2
    counts(2) = 0;
end

% 表格信息
col_names = {'就业', '失业'};
row_name = '数量 (人)';
main_title = '表 1 当前就业状态';
top_left_text = '当就业失业状态';
data_vals = counts;

% 图形窗口
figure('Position', [100, 100, 550, 250], 'Color', 'white');
axis off;
hold on;

% 表格参数
start_x = 0.2;
start_y = 0.6;
cell_width = 0.25;
cell_height = 0.2;

% 1. 左上角单元格（填空白）
rectangle('Position', [start_x - cell_width, start_y, cell_width, cell_height], ...
    'EdgeColor', 'black', 'LineWidth', 1.5);
text(start_x - cell_width/2, start_y + cell_height/2, top_left_text, ...
    'HorizontalAlignment', 'center', 'FontSize', 12);

% 2. 表头两列
for i = 1:2
    rectangle('Position', [start_x + (i-1)*cell_width, start_y, cell_width, cell_height], ...
        'EdgeColor', 'black', 'LineWidth', 1.5);
    text(start_x + (i-1)*cell_width + cell_width/2, start_y + cell_height/2, ...
        col_names{i}, 'HorizontalAlignment', 'center', 'FontSize', 12, 'FontWeight', 'bold');
end

% 3. 左边的行名单元格
rectangle('Position', [start_x - cell_width, start_y - cell_height, cell_width, cell_height], ...
    'EdgeColor', 'black', 'LineWidth', 1.5);
text(start_x - cell_width/2, start_y - cell_height/2, row_name, ...
    'HorizontalAlignment', 'center', 'FontSize', 12);

% 4. 填数据
for i = 1:2
    rectangle('Position', [start_x + (i-1)*cell_width, start_y - cell_height, cell_width, cell_height], ...
        'EdgeColor', 'black', 'LineWidth', 1.5);
    text(start_x + (i-1)*cell_width + cell_width/2, start_y - cell_height/2, ...
        num2str(data_vals(i)), 'HorizontalAlignment', 'center', ...
        'FontSize', 12, 'FontWeight', 'bold');
end

% 5. 标题 - 向左下偏一点
text(0.34, 0.85, main_title, 'HorizontalAlignment', 'center', ...
    'FontSize', 14, 'FontWeight', 'bold');

% 保存图像
exportgraphics(gcf, '表1_当前就业状态.png');
close(gcf);

% 相关性分析函数
function correlation_analysis(data, factor, factor_labels, factor_name)
    disp(['--- 相关性分析: ', factor_name, ' ---']);
    if ~iscategorical(data.(factor))
        data.(factor) = categorical(data.(factor));
    end
    actual_categories = categories(data.(factor));
    counts = crosstab(data.(factor), data.employment_status);
    employment_rate = counts(:, 1) ./ sum(counts, 2) * 100;
    if length(factor_labels) ~= length(actual_categories)
        warning('factor_labels 长度与实际分类数不匹配，使用实际分类标签');
        factor_labels = actual_categories;
    end
    results = table(factor_labels, counts(:, 1), counts(:, 2), employment_rate, ...
        'VariableNames', {factor_name, '就业人数', '失业人数', '就业率(%)'});
    disp(results);
end

% 回归分析函数
function regression_analysis(data, factor)
    disp(['--- 回归分析: ', factor, ' ---']);
    if ~iscategorical(data.(factor))
        data.(factor) = categorical(data.(factor));
    end
    X = dummyvar(data.(factor)); % one-hot 编码
    y = double(data.employment_status == '就业'); % 就业状态数值化
    mdl = fitglm(X(:, 1:end-1), y, 'Distribution', 'binomial'); % 逻辑回归
    disp(mdl);
end

% 绘图函数
function plot_employment_status(data, factor, factor_labels, title_str, filename)
    figure('Position', [100, 100, 800, 600]);
    counts = crosstab(data.(factor), data.employment_status);
    b = bar(1:length(factor_labels), counts);
    b(1).FaceColor = [0.2, 0.6, 0.8]; % 就业：蓝色
    b(2).FaceColor = [0.8, 0.3, 0.3]; % 失业：红色
    set(gca, 'XTick', 1:length(factor_labels), 'XTickLabel', factor_labels, 'XTickLabelRotation', 45);
    ylabel('人数');
    title(title_str);
    
    % 计算就业率
    total = sum(counts, 2);
    employment_rate = counts(:, 1) ./ total * 100; % 就业人数/总人数
    yyaxis right
    p = plot(1:length(factor_labels), employment_rate, '-o', 'LineWidth', 2, 'Color', [0, 0.5, 0], 'MarkerFaceColor', [0, 0.5, 0]);
    ylabel('就业率 (%)');
    ylim([0, 100]);
    
    % 设置图例，包含就业、失业和就业率
    legend([b(1), b(2), p], {'就业', '失业', '就业率'}, 'Location', 'best');
    
    % 保存图形
    saveas(gcf, filename);
    close(gcf);
end

% 生成五个就业图
% 1. 年龄段
plot_employment_status(data, 'age_group', age_labels, '按年龄段的就业状态分布', '年龄段就业状态.png');

% 2. 性别
plot_employment_status(data, 'sex', sex_labels, '按性别的就业状态分布', '性别就业状态.png');

% 3. 学历
edu_labels = categories(data.edu);
plot_employment_status(data, 'edu', edu_labels, '按学历的就业状态分布', '学历就业状态.png');

% 4. 专业
prof_labels = categories(data.prof);
plot_employment_status(data, 'prof', prof_labels, '按专业的就业状态分布', '专业就业状态.png');

% 5. 行业
industry_labels = categories(data.industry);
plot_employment_status(data, 'industry', industry_labels, '按行业的就业状态分布', '行业就业状态.png');



% 主程序调用
% 验证数据
disp('就业状态分布：');
summary(data.employment_status)

% 分析特征列表
factors = {'age_group', 'sex', 'edu', 'prof', 'industry'};
factor_labels = {
    categories(data.age_group),
    categories(data.sex),
    categories(data.edu),
    categories(data.prof),
    categories(data.industry)
};
factor_names = {'年龄段', '性别', '学历', '专业', '行业'};

% 运行分析和绘图
for i = 1:length(factors)
    % 相关性分析
    correlation_analysis(data, factors{i}, factor_labels{i}, factor_names{i});
    % 回归分析
    regression_analysis(data, factors{i});

end